<script>
import Header2 from "@/views/Components/Header/header.vue"
import Header3 from "@/views/Components/Header/header3.vue"
import {debounce, throttle} from '@/utils/statice'
import {getCartList, updateCartNum} from "@/api/shopCar/cart";
export default {
    components: {
        Header2,
        Header3
    },
    data() {
        return {
            CartList: [],
            multipleSelection: [],
            totalPrice: 0,
        };
    },
    computed: {},
    watch: {},
    methods: {
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleTotal() {
            let totalPrice = 0;
            this.multipleSelection.forEach(item => {
                totalPrice += item.price * item.num;
            })
            this.totalPrice = totalPrice;
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            this.handleTotal();
        },
        /**
         * 获取用户购物车数据
         */
        async getCartList() {
            let res = await getCartList();
            if(res.code === 200) {
                this.CartList = res.data;
            } else {
                this.$message({
                    message: res.message,
                    type: "error"
                });
            }
        },
        /**
         * 更新购物车商品数量根据主键id
         */
        async updateCart(id , num) {
            let res = await updateCartNum(id , num);
            if(res.code === 200) {
                this.$message({
                    message: "更新商品数量成功",
                    type: "success"
                });
                this.handleTotal();
            } else {
                this.$message({
                    message: res.message,
                    type: "error"
                });
            }
        },
        /**
         * 节流函数,改变购物车商品数量
         */
        handleChange: debounce(function (id , num) {
            console.log("商品id: " + id);
            console.log("商品数量: " + num);
            this.updateCart(id, num); // 执行修改
        }, 1000),
        selectAll() {
            this.$refs.multipleTable.toggleAllSelection();
        },
        /**
         * 删除商品封装
         */
        async deleteItem(ids) {
            await fetch("http://localhost:3310/shopCar", {
                method: "DELETE",
                headers: {
                    "Authorization": this.$store.getters.token,
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(ids)
            }).then(res => res.json())
            .then(data => {
                if(data.code === 200) {
                    this.$message({
                        message: "删除成功",
                        type: "success"
                    });
                    this.getCartList();
                    this.handleTotal();
                } else {
                    this.$message({
                        message: data.message,
                        type: "error"
                    });
                }
            })
        },
        /**
         * 删除购物车商品
         */
        deleteCart(id) {
            this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const ids = [id];
                this.deleteItem(ids);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            })
        },
        /**
         * 删除购物车商品
         */
        deleteCartAll() {
            if(this.multipleSelection.length === 0) {
                this.$message({
                    message: "请选择要删除的商品",
                    type: "warning"
                })
            } else {
                this.$confirm('此操作将永久删除选中的商品, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const ids = [];
                    console.log(this.multipleSelection);
                    this.multipleSelection.forEach(val => {
                        ids.push(val.id);
                    })
                    this.deleteItem(ids)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                })
            }
        },
        GoToSettle() {
            if(this.multipleSelection.length !== 0) {
                sessionStorage.setItem(
                    "selectItems",
                    JSON.stringify(this.multipleSelection)
                );
                this.$router.push({path: "/settlement"})
            } else {
                this.$message({
                    message: "当前没有选择需要结算的商品!",
                    type: "error"
                })
            }
        }
    },
    created() {
        this.getCartList();
    },
    mounted() {

    },
}
</script>

<template>
    <div id="AppCart">
        <Header2></Header2>
        <Header3></Header3>
        <div class="contain">
            <div class="tab">
                <el-table
                    max-height="540"
                    ref="multipleTable"
                    :data="CartList"
                    tooltip-effect="dark"
                    style="width: 100%;font-size: 15px;font-weight: 800;"
                    stripe
                    empty-text="当前购物车中没有商品...."
                    @selection-change="handleSelectionChange">
                    <el-table-column
                        align="center"
                        type="selection"
                        width="55">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="cover"
                        label="商品图片"
                        width="150">
                        <template slot-scope="scope">
                            <el-image style="width: 70px; height: 70px" :src="scope.row.cover" :preview-src-list="[scope.row.cover]">
                                <div slot="error" class="image-slot">
                                    <i class="el-icon-picture-outline"></i>
                                </div>
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="name"
                        label="商品名称"
                        width="300">
                        <template slot-scope="scope">
                            <span style="font-size: 16px">{{scope.row.name}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="price"
                        label="商品单价"
                        width="180"
                        >
                        <template slot-scope="scope">
                            <span style="font-size: 18px">￥{{scope.row.price}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="num"
                        label="数量"
                        width="200">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.num" @change="handleChange(scope.row.id, scope.row.num)" :min="1" :max="100" label="描述文字"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column
                        align="center"
                        label="小计"
                        width="180">
                        <template slot-scope="scope">
                            <span style="color: red;font-size: 20px">￥{{ (scope.row.price*scope.row.num).toFixed(2) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        align="center"
                        label="操作">
                        <template slot-scope="scope">
                            <el-button type="danger" icon="el-icon-delete" circle @click="deleteCart(scope.row.id)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="tFoot">
                    <div class="left">
                        <el-button style="transform: scale(0.8); font-size: 18px; font-weight: 800;" type="primary" @click="selectAll">全选</el-button>
                        <el-button style="transform: scale(0.8); font-size: 18px; font-weight: 800;" type="danger" @click="deleteCartAll">批量删除</el-button>
                    </div>
                    <div class="right">
                        <div class="r_l">
                            <div class="box1">
                                <span>总计：</span>
                                <span>￥</span>
                                <span class="total">{{ totalPrice }}</span>
                            </div>
                            <div class="box2">
                                <span>已选择</span>
                                <span class="sNum">{{ multipleSelection.length }}</span>
                                <span>件商品</span>
                            </div>
                        </div>
                        <div class="r_r">
                            <a href="#" class="buy" @click="GoToSettle">立即结算</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>


<style lang='scss' scoped>
@import url(../../assets/css/cart.css);
</style>
